<template>
  <Header />
  <div class="admin main box_center cf mb50">
    <div class="channelWrap">
      <el-row class="select-nav">
        <el-col :span="3" class="select-tag" :class="selectNav==='0'?'is-select':''" @click="select('0')">
          用户管理
        </el-col>
        <el-col :span="3" class="select-tag" :class="selectNav==='1'?'is-select':''" @click="select('1')">
          角色管理
        </el-col>
        <el-col :span="3" class="select-tag" :class="selectNav==='2'?'is-select':''" @click="select('2')">
          权限管理
        </el-col>
        <el-col :span="3" class="select-tag" :class="selectNav==='3'?'is-select':''" @click="select('3')">
          日志管理
        </el-col>
        <el-col :span="3" class="select-tag" :class="selectNav==='4'?'is-select':''" @click="select('4')">
          商品管理
        </el-col>
        <el-col :span="6"></el-col>
        <!-- 数据库管理按钮 -->
         <el-col :span="3">
          <el-button type="primary" @click="openPhpMyAdmin">详细数据库</el-button>
        </el-col>
      </el-row>
      <div v-if="selectNav==='0'">
        <el-table
        :data="users.filter(data => !userToSearch || data.username.toLowerCase().includes(userToSearch.toLowerCase()))"
        stripe style="width: 100%"
          size="large"
        >
          <el-table-column prop="id" label="用户id" width="80"></el-table-column>
          <el-table-column prop="username" label="用户名">
            <template #header>
              <span>用户名</span>
              <el-input v-model="userToSearch" size="small" placeholder="输入用户名以检索" style="width: 120px; margin-left: 15px"/>
            </template>
          </el-table-column>
          <el-table-column prop="create_time" label="创建时间" width="180"></el-table-column>
          <el-table-column prop="update_time" label="更新时间" width="180"></el-table-column>
          <el-table-column prop="role_name" label="用户角色" width="110"></el-table-column>
          <el-table-column prop="id" label="操作" width="200">
            <template  #default="scope">
              <el-button size="small" @click="toSetUser(scope.row.id, scope.row.role_id)">设置角色</el-button>
              <el-button type="primary" size="small" @click="toDeleteUser(scope.row.id)">删除用户</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-if="selectNav==='1'">
        <el-table :data="roles" stripe style="width: 100%" size="large">
          <el-table-column prop="id" label="角色id" width="80"></el-table-column>
          <el-table-column prop="name" label="角色名" width="200">
            <template #header>
              <span>角色名</span>
              <el-button size="small" style="margin-left: 15px" @click="toAddRole()">
                添加角色
              </el-button>
            </template>
          </el-table-column>
          <el-table-column prop="creator" label="创建者"></el-table-column>
          <el-table-column prop="create_time" label="创建时间" width="180"></el-table-column>
          <el-table-column prop="update_time" label="更新时间" width="180"></el-table-column>
          <el-table-column prop="id" label="操作" width="240">
            <template  #default="scope">
              <el-button size="small" @click="toSetRole(scope.row.permissions, scope.row.id)">编辑角色权限</el-button>
              <el-button type="primary" size="small" @click="toDeleteRole(scope.row.id)">删除角色</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-if="selectNav==='2'">
        <el-table :data="permissions" stripe style="width: 100%" size="large">
          <el-table-column prop="id" label="权限id" width="80"></el-table-column>
          <el-table-column prop="name" label="权限名"></el-table-column>
          <el-table-column prop="type" label="权限类型" width="100">
            <template #default="scope">
              <div v-if="scope.row.type==='0'">菜单</div>
              <div v-if="scope.row.type==='1'">按钮</div>
            </template>
          </el-table-column>
          <el-table-column prop="creator" label="创建者"></el-table-column>
          <el-table-column prop="createTime" label="创建时间"></el-table-column>
          <el-table-column prop="id" label="操作" width="200">
            <template  #default="scope">
              <el-button size="small" @click="toSetPermission(scope.row.id)">编辑权限</el-button>
              <el-button type="primary" size="small" @click="toDeletePermission(scope.row.id)">删除权限</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-if="selectNav === '3'">
        <el-table :data="logFiles" stripe style="width: 100%" size="large">
          <el-table-column prop="name" label="日志文件名"></el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button size="small" @click="showLogContent(scope.row.name)">查看内容</el-button>
              <el-button type="primary" size="small" @click="downloadLog(scope.row.name)">下载</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-dialog v-model:visible="showLogDialog" width="70%">
        <div v-html="currentLogContent"></div>
      </el-dialog>
      </div>
      <div v-if="selectNav==='4'">
        <el-table :data="goods" stripe style="width: 100%" size="large">
          <el-table-column
              prop="categoryName"
              label="类别" width="120"
              column-key="categoryName"
          />
          <el-table-column prop="bookName" label="宝贝名">
            <template #header>
              <span>宝贝名</span>
              <el-input v-model="search" size="small" style="width: 200px; margin-left: 10px; margin-right: 10px" placeholder="输入宝贝名搜索" />
              <el-button type="primary" size="small" @click="goodsSearch(search)">搜索</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="authorName" label="卖家" width="200" />
          <el-table-column prop="wordCount" width="100" label="价格" />
          <el-table-column prop="id" label="操作" width="200">
            <template  #default="scope">
              <el-button size="small" @click="goodsDetail(scope.row.id)">查看详情</el-button>
              <el-button type="primary" size="small" @click="goodsDelist(scope.row.id)">强制下架</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="tc mt10">
          <el-pagination
              small
              layout="prev, pager, next"
              :background="background"
              :page-size="pageSize"
              :total="total"
              @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
    <!-- 用户配置对话框 -->
    <el-dialog v-model="dialogSetUserVisible" title="设置用户角色" @close="cancelSetUser">
      <el-radio-group v-model="roleSelect">
        <el-radio v-for="(role, index) in roles" :label="role.id" :key="index">
          {{ role.name }}
        </el-radio>
      </el-radio-group>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelSetUser">
          取消修改
        </el-button>
        <el-button type="primary" @click="setUser(userSelect, roleSelect)">
          确认修改
        </el-button>
      </span>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogDeleteUserVisible" title="确认删除" @close="cancelDeleteUser" width="20%" class="delete-dialog">
      <div>
        <el-button @click="cancelDeleteUser">
          取消删除
        </el-button>
        <el-button type="primary" @click="confirmDeleteUser(userSelect)">
          确认删除
        </el-button>
      </div>
    </el-dialog>
    <!-- 角色配置对话框 -->
    <el-dialog v-model="dialogSetRoleVisible" title="编辑角色权限" @close="cancelSetRole">
      <el-checkbox-group v-model="permissionGroupSelect">
        <el-checkbox v-for="permission in permissionGroup" :key="permission.id" :label="permission.id">
          {{ permission.name }}
        </el-checkbox>
      </el-checkbox-group>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelSetRole">
          取消修改
        </el-button>
        <el-button type="primary" @click="setPermissionForRole(roleSelect, permissionGroupSelect)">
          确认修改
        </el-button>
      </span>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogAddRoleVisible" title="新增角色" @close="cancelAddRole">
      <div class="form-item">
        <span class="item-title">角色名称</span>
        <el-input v-model="newRoleForm.name" style="width: 80%; margin-left: 20px"/>
      </div>
      <div class="form-item">
        <div class="item-title" style="margin-bottom: 10px">角色权限</div>
        <el-checkbox-group v-model="newRoleForm.permissions">
          <el-checkbox v-for="permission in permissionGroup" :key="permission.id" :label="permission.id">
            {{ permission.name }}
          </el-checkbox>
        </el-checkbox-group>
      </div>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelAddRole">
          取消新建
        </el-button>
        <el-button type="primary" @click="addRole">
          确认新建
        </el-button>
      </span>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogDeleteRoleVisible" title="确认删除" @close="cancelDeleteRole" width="20%" class="delete-dialog">
      <div>
        <el-button @click="cancelDeleteRole">
          取消删除
        </el-button>
        <el-button type="primary" @click="confirmDeleteRole(roleSelect)">
          确认删除
        </el-button>
      </div>
    </el-dialog>
    <!-- 权限配置对话框 -->
    <el-dialog v-model="dialogSetPermissionVisible" title="编辑权限内容"  @close="cancelSetPermission">
      <el-form :model="formToSetPermission" label-width="120px">
        <el-form-item label="权限名">
          <el-input v-model="formToSetPermission.name" style="width: 80%"/>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelSetPermission">
          取消修改
        </el-button>
        <el-button type="primary" @click="setPermission(permissionSelect, formToSetPermission)">
          确认修改
        </el-button>
      </span>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogDeletePermissionVisible" title="确认删除" @close="cancelDeletePermission" width="20%" class="delete-dialog">
      <div>
        <el-button @click="cancelDeletePermission">
          取消删除
        </el-button>
        <el-button type="primary" @click="confirmDeletePermission(permissionSelect)">
          确认删除
        </el-button>
      </div>
    </el-dialog>
  </div>
  <Footer />
</template>

<script>
import Header from "@/components/common/Header";
import Footer from "@/components/common/Footer";
import "@/assets/styles/book.css";
import "@/assets/styles/admin.css";
import { reactive, toRefs, onMounted, ref, computed } from "vue";
import { useRouter} from "vue-router";
import { searchBooks } from "@/api/book";
import { delistGoods, deleteUser, deleteRole, deletePermission, getAllUser, getAllRole, getAllPermission, editUserRole, editRolePermission, addNewRole, editPermission  } from "@/api/admin";
import { ElMessage } from 'element-plus'

export default {
  data() {
    return {
      logFiles: [
        // 示例日志文件列表，应该根据你的实际文件名进行调整
        { name: 'debug.2023-12-10.0.log' },
        { name: 'debug.2023-12-10.1.log' },
        { name: 'debug.2023-12-10.2.log' },
        { name: 'debug.2023-12-11.0.log' },
        { name: 'debug.2023-12-11.1.log' },
        { name: 'debug.2023-12-11.2.log' },
        { name: 'debug.2023-12-11.3.log' },
        { name: 'debug.2023-12-11.4.log' },
        { name: 'debug.2023-12-11.5.log' },
        { name: 'debug.2023-12-11.6.log' },
        { name: 'debug.2023-12-11.7.log' },
        // ...其他文件
      ],
      showLogDialog: false,
      currentLogContent: ''
    };
  },
  methods: {
    openPhpMyAdmin() {
      // 更改浏览器标签标题
      // 打开新的 URL
      window.open('http://43.137.51.96:888/phpmyadmin_d1974124cf9e037d/index.php', '_blank');
    },
    showLogContent(fileName) {
      const logUrl = `https://gitee.com/yannnyiii/secondhand_frontend/raw/master/src/assets/logs/debug.2023-12-10.0.log`;
      window.open(logUrl, '_blank');
    },
    downloadLog(fileName) {
  const logUrl = `/gitee/yannnyiii/secondhand_frontend/raw/master/src/assets/logs/${fileName}`;
  fetch(logUrl)
    .then(response => response.blob())
    .then(blob => {
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = fileName;
      document.body.appendChild(link);
      link.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(link);
    })
    .catch(error => console.error('Error downloading log file:', error));
}
  },
  name: "Admin",
  components: {
    Header,
    Footer,
  },
  setup() {
    const router = useRouter();
    const state = reactive({
      selectNav: "0",
      users: [],
      roles: [],
      permissions: [],
      systemLog: [],
      goods: [],
      search: "",
      // 用户管理
      dialogSetUserVisible: false,
      userSelect: "", // 待设置的用户
      roleSelect: "0", // 待设置的角色
      dialogDeleteUserVisible: false,
      // 角色管理
      userToSearch: "",
      dialogSetRoleVisible: false,
      roleToEdit: "", // 待编辑权限的角色
      permissionGroup: [], // 权限组 [{name:"", id:""}]
      permissionGroupSelect: [], // 待设置的权限组 [permissionId]
      dialogDeleteRoleVisible: false,
      dialogAddRoleVisible: false,
      newRoleForm: {
        name: "",
        permissions: [],
      },  // 待提交的新角色表单
      // 权限管理
      dialogSetPermissionVisible: false,
      permissionSelect: "", // 待设置的权限
      formToSetPermission: {}, // 待提交的设置表单
      // 商品管理
      dialogDeletePermissionVisible: false,
      // pagination
      searchCondition: {},
      background: true,
      pageSize: 10,
      total: 0,
    });

    const select = (navId) => {
      state.selectNav = navId
    };

    // 用户管理
    const getUsers = async () => {
      const { data } = await getAllUser();
      state.users = data
    }
    const toSetUser = (userId, preUserRole) => {
      state.dialogSetUserVisible = true
      // 显示原角色
      state.roleSelect = preUserRole
      state.userSelect = userId
    };
    const cancelSetUser = () => {
      state.dialogSetUserVisible = false
      state.roleSelect = ""
      state.userSelect = ""
    }
    const setUser = async (userId, roleId) => {
      console.log("设置角色权限")
      console.log(userId, roleId)
      state.dialogSetUserVisible = false
      await editUserRole({"user_id": parseInt(userId), "role_id": parseInt(roleId)})
      const { data } = await getAllUser();
      state.users = data
    };
    const toDeleteUser = (userId) => {
      state.dialogDeleteUserVisible = true
      state.userSelect = userId
    };
    const confirmDeleteUser = async (userId) => {
      console.log("删除用户" + userId)
      state.dialogDeleteUserVisible = false
      await deleteUser(parseInt(userId));
      const { data } = await getAllUser();
      state.users = data
    };
    const cancelDeleteUser = () => {
      state.dialogDeleteUserVisible = false
      state.userSelect = ""
    };

    // 角色管理
    const getRoles =  async () => {
      const { data } = await getAllRole();
      state.roles = data
    };
    const toSetRole = (prePermissionGroup, roleId) => {
      state.dialogSetRoleVisible = true
      state.roleSelect = roleId
      // 统计已选的权限
      for (let i=0; i<prePermissionGroup.length; i++) {
        state.permissionGroupSelect.push(prePermissionGroup[i].id)
      }
    };
    const cancelSetRole = () => {
      state.dialogSetRoleVisible = false
      state.permissionGroupSelect = []
      state.roleSelect = ""
    }
    const setPermissionForRole = async (roleId, permissions) => {
      state.dialogSetRoleVisible = false
      // 格式调整为后端需要的
      let new_permissions = []
      for (let i=0; i<permissions.length; i++) {
        new_permissions.push(parseInt(permissions[i]))
      }
      let param = {
        "role_id": parseInt(roleId),
        "permissions": new_permissions,
      }
      console.log("为角色赋权")
      console.log(param)
      await editRolePermission(param)
      const { data } = await getAllRole();
      state.roles = data
    };
    const toDeleteRole = (roleId) => {
      state.dialogDeleteRoleVisible = true
      state.roleSelect = roleId
    };
    const confirmDeleteRole = async (roleId) => {
      state.dialogDeleteRoleVisible = false
      await deleteRole(parseInt(roleId));
      const { data } = await getAllRole();
      state.roles = data
      await getUsers()
    };
    const cancelDeleteRole = () => {
      state.dialogDeleteRoleVisible = false
      state.roleSelect = ""
    };
    const toAddRole = () => {
      state.newRoleForm = {
        name: "",
        permissions: [],
      }
      state.dialogAddRoleVisible = true
    }
    const addRole = async () => {
      console.log(state.newRoleForm)
      state.dialogAddRoleVisible = false
      // 格式调整为后端需要的
      let new_permissions = []
      for (let i=0; i<state.newRoleForm.permissions.length; i++) {
        new_permissions.push(parseInt(state.newRoleForm.permissions[i]))
      }
      state.newRoleForm.permissions = new_permissions
      console.log("新建角色")
      console.log(state.newRoleForm)
      await addNewRole(state.newRoleForm)
      const { data } = await getAllRole();
      state.roles = data
    }
    const cancelAddRole = () => {
      state.dialogAddRoleVisible = false
    }

    // 权限管理
    const getPermissions = async () => {
      const { data } = await getAllPermission()
      state.permissions = data
      // 初始化权限组，用于渲染多选框
      state.permissionGroup = []
      for (let i=0; i<state.permissions.length; i++) {
        state.permissionGroup.push({"id": state.permissions[i].id, "name": state.permissions[i].name})
      }
    };
    const toSetPermission = (permissionId) => {
      state.dialogSetPermissionVisible = true
      state.permissionSelect = permissionId
    };
    const cancelSetPermission = () => {
      state.formToSetPermission = {}
      state.permissionSelect = ""
      state.dialogSetPermissionVisible = false
    };
    const setPermission = async (permissionId, form) => {
      if (form.name === undefined || form.name === "") {
        ElMessage({
          message: '权限名不能为空',
          type: 'warning',
        })
      } else {
        // 调接口
        let param = {
          "id": permissionId,
          "name": form.name
        }
        console.log("编辑权限")
        console.log(param)
        await editPermission(param)
        await getPermissions()
        await getRoles()
      }
      state.dialogSetPermissionVisible = false
    };
    const toDeletePermission = (permissionId) => {
      state.dialogDeletePermissionVisible = true
      state.permissionSelect = permissionId
    };
    const confirmDeletePermission = async (permissionId) => {
      state.dialogDeletePermissionVisible = false
      await deletePermission(parseInt(permissionId));
      await getPermissions()
      await getRoles()
    };
    const cancelDeletePermission = () => {
      state.dialogDeletePermissionVisible = false
      state.permissionSelect = ""
    };

    // 商品管理
    const goodsDetail = (goodsId) => {
      router.push({ path: `/book/${goodsId}` });
    };
    const goodsDelist = async (goodsId) => {
      for (let i=0; i<state.goods.length; i++ ) {
        if (state.goods[i].id === goodsId) {
          state.goods.splice(i, 1)
        }
      }
      ElMessage({
        message: '强制下架成功',
        type: 'success',
      })
    };
    const goodsSearch = async (key) => {
      state.searchCondition = { keyword: key };
      searchGoods();
    };
    const handleCurrentChange = (pageNum) => {
      state.searchCondition.pageNum = pageNum;
      searchGoods();
    };
    const searchGoods = async () => {
      const { data } = await searchBooks(state.searchCondition);
      state.goods = data.list;
      state.searchCondition.pageNum = data.pageNum;
      state.searchCondition.pageSize = data.pageSize;
      state.total = Number(data.total);
    };

    onMounted(async () => {
      state.searchCondition.keyword = "";
      state.searchCondition.pageSize = 10;
      state.searchCondition.categoryId = null;
      await searchGoods();
      await getUsers();
      await getRoles();
      await getPermissions();
      // await getlogs();
    });

    return {
      ...toRefs(state),
      select,
      // 用户管理
      toSetUser,
      setUser,
      cancelSetUser,
      toDeleteUser,
      confirmDeleteUser,
      cancelDeleteUser,
      // 角色管理
      toSetRole,
      setPermissionForRole,
      cancelSetRole,
      toDeleteRole,
      confirmDeleteRole,
      cancelDeleteRole,
      toAddRole,
      addRole,
      cancelAddRole,
      // 权限管理
      toSetPermission,
      cancelSetPermission,
      setPermission,
      confirmDeletePermission,
      toDeletePermission,
      cancelDeletePermission,
      // 商品管理
      goodsDetail,
      goodsDelist,
      goodsSearch,
      handleCurrentChange,
    };
  },

}
</script>

<style scoped>

</style>